package aesEncode;

import android.app.Activity;
import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.PluginRegistry;
/*
* Aesc加密
* */
public class AesEncodePlugin implements MethodChannel.MethodCallHandler {
    public static final String CHANNEL = "xinAnLi";
    static MethodChannel channe;
    private static final String KEY = "youkon0123456789";

    public static void registerWith(FlutterEngine flutterEngine, Activity activity12) {
        channe = new MethodChannel(flutterEngine.getDartExecutor(), CHANNEL);
        AesEncodePlugin plugin = new AesEncodePlugin();
        channe.setMethodCallHandler(plugin);
    }

    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        try {
            if (methodCall.method.equals("passwordAes")) {
                String pwd = (String) methodCall.arguments;
                byte[] pwdBytes = cipherOperation(pwd, Cipher.ENCRYPT_MODE);
                String pwdEncode = Base64.encodeToString(pwdBytes, Base64.DEFAULT);
                result.success(pwdEncode.trim());
            } else {
                result.notImplemented();
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.success("");
        }
    }


    public static byte[] cipherOperation(String content, int mode) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
        byte[] contentBytes = content.getBytes("utf-8");
        byte[] keyBytes = KEY.getBytes("utf-8");
        byte[] iv = KEY.getBytes("utf-8");
        SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");

        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(mode, secretKey, ivParameterSpec);
        return cipher.doFinal(contentBytes);
    }
}
